//
//  RegisterViewController.m
//  League
//
//  Created by 博宇 李 on 2018/1/22.
//  Copyright © 2018年 ciyuanjuzhen. All rights reserved.
//

#import "RegisterViewController.h"
#import "RegisterTextFiledView.h"

#import "MyPreferencesViewController.h"
#import "LinkdInAlertView.h"
#import "LinkedInHelper.h"
#import "MyProfileViewController.h"
#import "PGGDropView.h"
#import "ProfileManager.h"

#define kTextFiledBgColor [UIColor colorWithRed:250/255.0 green:250/255.0 blue:250/255.0 alpha:1]

@interface RegisterViewController ()<PGGDropDelegate>
{
    NSBundle *bundle;
    NSInteger selectNumIndex;
    NSArray *counterNum;
}
@property(strong , nonatomic)RegisterTextFiledView *registerView;
@property (nonatomic ,assign)NSInteger CountDown;
@property(strong,nonatomic)PGGDropView * dropView;
//定时器

@property (nonatomic ,strong)NSTimer *countDownTimer;
@property (nonatomic ,strong)NSTimer *Timer;
@property(strong , nonatomic)LinkdInAlertView *linkInAlertV;
@property (strong, nonatomic) NSString *registerCode;
@property (strong, nonatomic) NSString *LinkInConfiguration;
@property (strong, nonatomic) ProfileManager *manager;

@end

@implementation RegisterViewController

- (void)backStartTime

{
    
    //设置倒计时总时长
    self.registerView.getCodeBtn.enabled = NO;
    [self.Timer invalidate];
    self.CountDown = 60;
    self.Timer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(TimeNSTimer) userInfo:nil repeats:YES];
    
}

//使用NSTimer实现倒计时
- (void)TimeNSTimer
{
    self.CountDown --;
    [self.registerView.getCodeBtn setTitle:[NSString stringWithFormat:@"%@",@(self.CountDown)] forState:UIControlStateNormal];
    if (self.CountDown == 0) {
        [self.Timer setFireDate:[NSDate distantFuture]];
        self.registerView.getCodeBtn.enabled = YES;
        [InternationalControl initUserLanguage];//初始化应用语言
        NSBundle *bundle = [InternationalControl bundle];
        [self.registerView.getCodeBtn setTitle:[bundle localizedStringForKey:@"getCode" value:nil table:@"hello"] forState:UIControlStateNormal];
    }
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    self.navigationController.navigationBarHidden = NO;
}

- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    self.navigationController.navigationBarHidden = NO;
}
- (void)viewDidLoad {
    [super viewDidLoad];
//   self.title = @"注册";
    self.manager = [ProfileManager shareManager];
    selectNumIndex = 0;
    counterNum = [NSArray arrayWithObjects:@"+86",@"+852", nil];
    
    [self setupRegisterView];
    [self changLau];
    
    [self getLinkInConfiguration];
    // Do any additional setup after loading the view.
}

- (void)getLinkInConfiguration {
    NSDictionary *dic = @{
                          @"keyWord":@"LinkedInAuth"
                          };
    NSString *urlStr = [NSString stringWithFormat:@"%@%@",kFirstUrl,kConfigurationUrl];
    NSLog(@"urlStr:%@",urlStr);
    [DataContrller PostRequestUrl:urlStr Param:dic requestSuccess:^(NSDictionary *backDic) {
        NSLog(@"backDic:%@",backDic);
        if ([backDic[@"returnCode"] integerValue] == 200) {
            self.LinkInConfiguration = backDic[@"obj"];
        } else {
//            [self showAlert:backDic[@"msg"]];
        }
    } requestFail:^(NSString *backErrorStr) {
        
        NSLog(@"backErrorStr:%@",backErrorStr);
    
    }];
}

-(void)changLau
{
    
    
    [InternationalControl initUserLanguage];//初始化应用语言
    NSBundle *bundle = [InternationalControl bundle];
    
    if (self.isForget == YES) {
         self.title =  [bundle localizedStringForKey:@"find" value:nil table:@"hello"];
        [self.registerView.registerBtn setTitle:[bundle localizedStringForKey:@"over" value:nil table:@"hello"] forState:UIControlStateNormal];
    }
    else
    {
         self.title =  [bundle localizedStringForKey:@"regis" value:nil table:@"hello"];
         [self.registerView.registerBtn setTitle:[bundle localizedStringForKey:@"Next" value:nil table:@"hello"] forState:UIControlStateNormal];
    }
    
    
    [self.registerView.getCodeBtn setTitle:[bundle localizedStringForKey:@"getCode" value:nil table:@"hello"] forState:UIControlStateNormal];
    
    self.registerView.userNameTf.placeholder =[bundle localizedStringForKey:@"PhonePlaceholder" value:nil table:@"hello"];
    
    self.registerView.userCodeTf.placeholder =[bundle localizedStringForKey:@"getCode" value:nil table:@"hello"];
    self.registerView.passWordTf.placeholder =[bundle localizedStringForKey:@"PasswordTf" value:nil table:@"hello"];
    
//    self.registerView.userPassWordTf.placeholder =[bundle localizedStringForKey:@"PwPlaceholder" value:nil table:@"hello"];
    
    
}
-(void)setupRegisterView
{
    self.registerView = [[RegisterTextFiledView alloc ] initWithFrame:CGRectMake(0, 0, self.view.width, self.view.height)];
    [self.registerView.registerBtn addTarget:self action:@selector(linkIn:) forControlEvents:UIControlEventTouchDown];
    [self.registerView.getCodeBtn addTarget:self action:@selector(getCodeBtn:) forControlEvents:UIControlEventTouchDown];
    self.registerView.getCodeBtn.enabled = YES;
    [self.registerView.linkIn addTarget:self action:@selector(linkIn:) forControlEvents:UIControlEventTouchDown];
    [self.registerView.countryNumberBtn setTitle:counterNum[selectNumIndex] forState:UIControlStateNormal];
    [self.registerView.countryNumberBtn addTarget:self action:@selector(counterNum:) forControlEvents:UIControlEventTouchDown];
    
    [self.view addSubview:self.registerView];
    if (self.isForget == YES) {
        self.registerView.linkIn.hidden = YES;
        
        //找回密码 pass与验证码交换位置
        CGRect passwordRect = self.registerView.passWordTf.frame;
        CGRect codeRect = self.registerView.userCodeTf.frame;
        CGRect codeBtnRect = self.registerView.getCodeBtn.frame;
        
        CGRect newCodeRect;
        newCodeRect.origin.x = passwordRect.origin.x;
        newCodeRect.origin.y = passwordRect.origin.y;
        newCodeRect.size.width = codeRect.size.width;
        newCodeRect.size.height = codeRect.size.height;
        
        CGRect newPasswordRect;
        newPasswordRect.origin.x = codeRect.origin.x;
        newPasswordRect.origin.y = codeRect.origin.y;
        newPasswordRect.size.width = passwordRect.size.width;
        newPasswordRect.size.height = passwordRect.size.height;
        
        CGRect newCodeBtnRect;
        newCodeBtnRect.origin.x = codeBtnRect.origin.x;
        newCodeBtnRect.origin.y = passwordRect.origin.y;
        newCodeBtnRect.size.width = codeBtnRect.size.width;
        newCodeBtnRect.size.height = codeBtnRect.size.height;
        
        self.registerView.passWordTf.frame = newPasswordRect;
        self.registerView.userCodeTf.frame = newCodeRect;
        self.registerView.getCodeBtn.frame = newCodeBtnRect;
        
    } else {
        self.registerView.linkIn.hidden = YES;
    }
    
    
    
}

- (void)counterNum:(UIButton *)btn
{
    /*
    [self.dropView removeFromSuperview];
    self.dropView = [[PGGDropView alloc] initWithFrame:CGRectMake(0, 0 ,self.view.width, 100) withTitleArray:counterNum];
    self.dropView.center = CGPointMake(self.view.width/2, self.view.height/2);
    self.dropView.backgroundColor = kTextFiledBgColor;
    [self.dropView beginAnimation];
    self.dropView.delegate = self;
    [self.view addSubview:self.dropView];
     */
    UIAlertController *alertVc = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];
    UIAlertAction *cancle = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction *_Nonnull action) {
       
    }];
    UIAlertAction *walkingBtn = [UIAlertAction actionWithTitle:@"+86" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
        selectNumIndex = 0;
        [self.registerView.countryNumberBtn setTitle:counterNum[selectNumIndex] forState:UIControlStateNormal];
    }];
    UIAlertAction *gaodeNavigation = [UIAlertAction actionWithTitle:@"+852" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        selectNumIndex = 1;
        [self.registerView.countryNumberBtn setTitle:counterNum[selectNumIndex] forState:UIControlStateNormal];
    }];
    
    [alertVc addAction:cancle];
    [alertVc addAction:walkingBtn];
    [alertVc addAction:gaodeNavigation];
    [self presentViewController:alertVc animated:YES completion:nil];
}

- (void)PGGDropView:(PGGDropView *)DropView didSelectAtIndex:(NSInteger )index{
    
    NSLog(@"%ld",index);
    NSInteger ind = index - 100;
    
    selectNumIndex = ind;
    [self.registerView.countryNumberBtn setTitle:counterNum[selectNumIndex] forState:UIControlStateNormal];
    //    cityNameLab = cityList[ind];
    
}

- (void)linkIn:(UIButton *)sender
{
    if (self.isForget == YES) {
        [self resetPasswordRequest];
        return;
    }
    
    self.manager.areaCode = counterNum[selectNumIndex];
    self.manager.phone = self.registerView.userNameTf.text;
    self.manager.password = self.registerView.passWordTf.text;
    
    if ([self.registerView.userNameTf.text isEqualToString:@""]) {
        [self showAlert:@"请输入手机号"];
        return;
    }
    if ([self.registerView.passWordTf.text isEqualToString:@""]) {
        [self showAlert:@"请输入密码"];
        return;
    }
    
    if (![self.registerCode isEqualToString:self.registerView.userCodeTf.text]) {
        [self showAlert:@"验证码错误"];
        return;
    }
    
    LinkedInHelper *linkedIn = [LinkedInHelper sharedInstance];
    
    // If user has already connected via linkedin in and access token is still valid then
    // No need to fetch authorizationCode and then accessToken again!
    
    /*
    if (linkedIn.isValidToken) {
        
        linkedIn.customSubPermissions = [NSString stringWithFormat:@"%@,%@", first_name, last_name];
        
        // So Fetch member info by elderyly access token
        [linkedIn autoFetchUserInfoWithSuccess:^(NSDictionary *userInfo) {
            // Whole User Info
            
            NSString * desc = [NSString stringWithFormat:@"first name : %@\n last name : %@", userInfo[@"firstName"], userInfo[@"lastName"] ];
            
            NSLog(@"user Info : %@", userInfo);
            NSLog(@"user Info : %@", desc);
        } failUserInfo:^(NSError *error) {
            NSLog(@"error : %@", error.userInfo.description);
        }];
    } else {
     */
    linkedIn.cancelButtonText = @"Close"; // Or any other language But Default is Close
    NSInteger profile;
    if (self.LinkInConfiguration == nil) {
        profile = BasicProfile;
    } else {
        if ([self.LinkInConfiguration isEqualToString:@"BasicProfile"]) {
            profile = BasicProfile;
        } else {
            profile = FullProfile;
        }
    }
        NSArray *permissions = @[@(profile),
                                 @(EmailAddress),
                                 @(Share),
                                 @(CompanyAdmin)];
        
        linkedIn.showActivityIndicator = YES;
        
#warning - Your LinkedIn App ClientId - ClientSecret - RedirectUrl - And state
        
        [linkedIn requestMeWithSenderViewController:self
                                           clientId:@"81wvfyy9p6hh3z"
                                       clientSecret:@"4BkmGWxEQjIqnG4B"
                                        redirectUrl:@"http://localhost:8080/quick4j/rest/linkedin/getuserinfo"
                                        permissions:permissions
                                              state:@""
                                    successUserInfo:^(NSDictionary *userInfo) {
                                        
                                        //                                        self.btnLogout.hidden = !linkedIn.isValidToken;
                                        
                                        NSString * desc = [NSString stringWithFormat:@"first name : %@\n last name : %@",
                                                           userInfo[@"firstName"], userInfo[@"lastName"] ];
                                        NSLog(@"user Info : %@", desc);
                                        
                                        // Whole User Info
                                        NSLog(@"user Info : %@", userInfo);
                                        // You can also fetch user's those informations like below
                                        NSLog(@"job title : %@",     [LinkedInHelper sharedInstance].title);
                                        NSLog(@"company Name : %@",  [LinkedInHelper sharedInstance].companyName);
                                        NSLog(@"email address : %@", [LinkedInHelper sharedInstance].emailAddress);
                                        NSLog(@"Photo Url : %@",     [LinkedInHelper sharedInstance].photo);
                                        NSLog(@"Industry : %@",      [LinkedInHelper sharedInstance].industry);
                                        
                                        ProfileManager *manager = [ProfileManager shareManager];
                                        manager.email = userInfo[@"emailAddress"];
                                        manager.username = userInfo[@"formattedName"];
                                        if (manager.professionsArray == nil) {
                                            manager.professionsArray = [NSMutableArray array];
                                        }
                                        [manager.professionsArray addObject:userInfo[@"headline"] == nil ? @"" : userInfo[@"headline"]];
                                        manager.linkedInAccessToken = userInfo[@"id"];
                                        
                                        if (self.isForget == YES) {
                                            [self.navigationController popViewControllerAnimated:YES];
                                        }else
                                        {
                                            MyProfileViewController *myProfileVc = [[MyProfileViewController alloc] init];
                                            myProfileVc.isRegister = YES;
                                            [self.navigationController pushViewController:myProfileVc animated:YES];
                                        }
                                    } cancelBlock:^{
                                        NSLog(@"User cancelled the request Action");
                                        //                                        self.btnLogout.hidden = NO;
                                    } failUserInfoBlock:^(NSError *error) {
                                        NSLog(@"error : %@", error.userInfo.description);
                                        //                                        self.btnLogout.hidden = !linkedIn.isValidToken;
                                    }
         ];
//    }
}
-(void)alert
{
    [self.linkInAlertV removeFromSuperview];
    self.linkInAlertV = [[LinkdInAlertView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, kScreenHeight)];
    [[UIApplication sharedApplication].keyWindow addSubview:self.linkInAlertV];
}
- (void)registerBtn:(UIButton *)sender
{
    if (self.isForget == YES) {
         [self.navigationController popViewControllerAnimated:YES];
    } else {
        MyPreferencesViewController *myPreferencesVc = [[MyPreferencesViewController alloc] init];
        myPreferencesVc.isRegister = YES;
        [self.navigationController pushViewController:myPreferencesVc animated:YES];
    }
}
-(void)getCodeBtn:(UIButton *)sender
{
    NSDictionary *dic = @{
                          @"phone":self.registerView.userNameTf.text,
                          @"areaNo":counterNum[selectNumIndex]
                          };
    NSString *urlStr = [NSString stringWithFormat:@"%@%@",kFirstUrl,kRegisterCode];
    NSLog(@"urlStr:%@",urlStr);
    [DataContrller PostRequestUrl:urlStr Param:dic requestSuccess:^(NSDictionary *backDic) {
        NSLog(@"backDic:%@",backDic);
        if ([backDic[@"returnCode"] integerValue] == 200) {
//            self.registerView.userCodeTf.text = backDic[@"obj"][@"phonecode"];
            self.registerCode = backDic[@"obj"][@"phonecode"];
        } else if ([backDic[@"returnCode"] integerValue] == 404)  {
            [self showAlert:@"手机号码不存在"];
        } else {
            [self showAlert:backDic[@"msg"]];
        }
    } requestFail:^(NSString *backErrorStr) {
        
        NSLog(@"backErrorStr:%@",backErrorStr);
        [self showAlert:backErrorStr];
        
    }];

    [self backStartTime];
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)resetPasswordRequest {
    if ([self.registerView.userNameTf.text isEqualToString:@""]) {
        [self showAlert:@"请输入手机号"];
        return;
    }
    if (![self.registerCode isEqualToString:self.registerView.userCodeTf.text]) {
        [self showAlert:@"验证码错误"];
        return;
    }
    if ([self.registerView.passWordTf.text isEqualToString:@""]) {
        [self showAlert:@"请输入密码"];
        return;
    }

    NSDictionary *dic = @{
                          @"phone":self.registerView.userNameTf.text,
                          @"password":self.registerView.passWordTf.text
                          };
    NSString *urlStr = [NSString stringWithFormat:@"%@%@",kFirstUrl,kResetPassword];
    NSLog(@"urlStr:%@",urlStr);
    [DataContrller PostRequestUrl:urlStr Param:dic requestSuccess:^(NSDictionary *backDic) {
        NSLog(@"backDic:%@",backDic);
        if ([backDic[@"returnCode"] integerValue] == 200) {
            [self.navigationController popViewControllerAnimated:YES];
        } else {
            [self showAlert:backDic[@"msg"]];
        }
    } requestFail:^(NSString *backErrorStr) {
        
        NSLog(@"backErrorStr:%@",backErrorStr);
        [self showAlert:backErrorStr];
    }];
}

@end
